
use std::str::FromStr;

use reqwest::{
    Result,
};
use serde_json::{
    Value,
};

pub struct Artist {
    id: u64,
    name: String,
    avatar: String,
}

pub struct Album {
    id: u64,
    name: String,
    size: u64,
}

pub struct SongInfo {
    pub id: u64,
    pub name: String,
    pub duration: u64,
    artist: Artist,
    album: Album,
}

impl Artist {
    pub fn new(id: u64, name: String, avatar: String) -> Self {
        Artist {
            id,
            name,
            avatar,
        }
    }
}

impl Album {
    pub fn new(id: u64, name: String, size: u64) -> Self {
        Album {
            id,
            name,
            size,
        }
    }
}

impl SongInfo {
    pub fn new(id: u64, name: String, duration: u64, artist: Artist, album: Album) -> Self {
        SongInfo {
            id,
            name,
            duration,
            artist,
            album,
        }
    }

    pub fn get_url(&self) -> Result<String> {
        let url = format!("{}/song/url?id={}",  super::BASE_URL, self.id);
        let response = reqwest::get(&url)?.text()?;
        let value: Value = serde_json::from_str(&response).unwrap();

        let url: String = String::from_str(&value["data"][0]["url"].as_str().unwrap_or("null")).unwrap();

        Ok(url)
    }

    pub fn can_play(&self) -> bool {
        let url = format!("{}/check/music?id={}",   super::BASE_URL, self.id);
        let response = reqwest::get(&url).unwrap().text().unwrap();
        let value: Value = serde_json::from_str(&response).unwrap();

        let yes = &value["success"].as_bool().unwrap_or(false);
        *yes
    }
}